import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:sample2/components/notification/theme.dart';
import 'package:sample2/components/notification/user_info.dart';
import 'package:sample2/helper/app_helper.dart';
import 'package:sample2/helper/chat_helper.dart';
import 'package:sample2/pages/chat/chat.dart' deferred as chat;
import 'package:sample2/pages/chat/chat_conversation.dart' deferred as chat_conversation;
import 'package:sample2/pages/chat/chat_group/chat_group_list.dart' deferred as chat_group;
import 'package:sample2/pages/samples/popuppage/my_popup_route.dart';
import 'package:sample2/pages/samples/animation/animationpage.dart' deferred as animationpage;
import 'package:sample2/pages/samples/listview/recycle_page.dart' deferred as recycle_page;
import 'package:sample2/pages/login/register.dart' deferred as register;
import 'package:sample2/pages/home/home_page.dart';
import 'package:sample2/pages/samples/webviewsample/webview_page.dart' deferred as webview_page;
import 'package:sample2/pages/samples/samples.dart' deferred as samples;
import 'package:sample2/pages/settings/settings.dart' deferred as settings;
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'package:sample2/utils/networking.dart';
// import "package:google_fonts/google_fonts.dart" deferred as google_fonts;

void main(){
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return MyAppState();
  }
}

class MyAppState extends State {
  Locale? _locale;
  String fontFamily = "Roboto";
  bool hasLogin = false;
  bool hasConnectedToChat = false;
  @override
  void initState() {
    AppHelper.shared.getCurrentLanguageCode().then((value) {
      if(mounted){
        setState(() {
          String langCode = value ?? "en";
          _locale = Locale.fromSubtags(languageCode: langCode);
          fontFamily = AppHelper.shared.getCorrespondingFontFamilyName(langCode);
        });
      }
    });
    AppHelper.shared.getUserInfo().then((value) {
      if(mounted){
        setState(() {
          hasLogin = AppHelper.shared.userInfo?.token?.isNotEmpty ?? false;
        });
      }
    });
    NetworkUtil.dissmissUI = (){
      EasyLoading.dismiss();
    };
    super.initState();
  }

  Route<dynamic>? _generateRoute(RouteSettings settings) {
    switch (settings.name) {
      case MyPopupRoute.routeName:
        return MyPopupRoute();
    }
    return null;
  }

  WidgetBuilder buildWidget(Widget targetWidget) {
      return ((BuildContext context) => targetWidget);
  }
//when login state changed will call this
  @override
  void didChangeDependencies(){
    if(hasLogin){
      EasyLoading.show();
      ChatHelper.initialAndConnectToChatServer(() {
        EasyLoading.dismiss();
        setState(() {
          hasConnectedToChat = true;
        });
      }, (int code, String message) {});
    }
    super.didChangeDependencies();
  }

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    EasyLoading.instance
      ..loadingStyle = EasyLoadingStyle.light
      ..indicatorColor = Colors.blue
      ..progressColor = Colors.red;
    //add global listener for local
    return NotificationListener(
      child: MaterialApp(
        title: 'Flutter Demo',
        locale: _locale,
        localizationsDelegates: const [
          AppLocalizations.delegate,
          GlobalWidgetsLocalizations.delegate,
          GlobalMaterialLocalizations.delegate,
          GlobalCupertinoLocalizations.delegate
        ],
        supportedLocales: const [
          Locale("en", ""),
          Locale("zh"),
          Locale("es", "")
        ],
        debugShowCheckedModeBanner: false,
        theme: ThemeData(
            // This is the theme of your application.
            //
            // Try running your application with "flutter run". You'll see the
            // application has a blue toolbar. Then, without quitting the app, try
            // changing the primarySwatch below to Colors.green and then invoke
            // "hot reload" (press "r" in the console where you ran "flutter run",
            // or simply save your changes to "hot reload" in a Flutter IDE).
            // Notice that the counter didn't reset back to zero; the application
            // is not restarted.
            primarySwatch: Colors.blue,
            fontFamily: fontFamily),
        onGenerateRoute: _generateRoute,
        home:buildWidget(const MyHomePage())(context),
        builder: EasyLoading.init(),
        routes: <String, WidgetBuilder>{
          "/settings": buildWidget(FutureBuilder(future: settings.loadLibrary(),builder:(context, snapshot) =>settings.Settings())),
          "/register":buildWidget(FutureBuilder(future: register.loadLibrary(),builder:(context, snapshot) => register.Register())),
          "/samples":buildWidget(FutureBuilder(future: samples.loadLibrary(),builder:(context, snapshot) => samples.Samples())),
          "/chat": buildWidget(FutureBuilder(future: chat.loadLibrary(),builder:(context, snapshot) => chat.Chat())),
          "/chatMessage": buildWidget(FutureBuilder(future: chat_conversation.loadLibrary(),builder:(context, snapshot) => chat_conversation.ChatConversation())),
          "/chatGroup": buildWidget(FutureBuilder(future: chat_group.loadLibrary(),builder:(context, snapshot) => chat_group.ChatGroupList())),
          "/animations": buildWidget(FutureBuilder(future: animationpage.loadLibrary(),builder:(context, snapshot) => animationpage.AnimationPage())),
          "/recycleview": buildWidget(FutureBuilder(future: recycle_page.loadLibrary(),builder:(context, snapshot) => recycle_page.RecyclePage())),
          "/webview":buildWidget(FutureBuilder(future: webview_page.loadLibrary(),builder:(context, snapshot) => webview_page.WebViewPage()))
        }
      ),
      onNotification: (notification) {
        if (notification.runtimeType == AppLocaleNotification) {
          setState(() {
            _locale = AppHelper.shared.getCurrentLocale();
            fontFamily = AppHelper.shared
                .getCorrespondingFontFamilyName(_locale?.languageCode ?? "en");
          });
        }else if(notification.runtimeType == LoginActionNotification){
          setState(() {
            hasLogin = true;
          });
        }
        return true;
      },
    );

  }

  @override
  void dispose() {
    ChatHelper.disconnect();
    super.dispose();
  }
}
